function Run-ContentDeploymentJobForImport
{
Param(
  [Parameter(Mandatory=$false,Position=1)][string]$Identity,
  [Parameter(Mandatory=$false,Position=2)][string]$OverrideSchemaVersion,
  [Parameter(Mandatory=$false,Position=3)][bool]$IgnoreRequirements,
  [Parameter(Mandatory=$false,Position=4)][bool]$ReCreateSiteCollection,
  [Parameter(Mandatory=$false,Position=5)][bool]$CreateIfNotExistSiteCollection,
  [Parameter(Mandatory=$false,Position=6)][bool]$DefaultMasterPage
)
	[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

	$fatalError = $false
	$job = Get-ContentDeploymentJob $Identity
	if ( $job -eq $null) 
	{
		Write-Host "Job $identity not found."
		return;
	}
	
	$token = Get-TokenForJob -Job $Job.Name
	if ( $token -eq $null) 
	{
		Write-Host "No valid token for job $identity. Consider resetting status using Cmdlet Change-TokenImportedStatus -Timestamp [TokenDateTimeFormat] -Imported [bool]"
		return;	
	}
	
	$settings = New-Object Microsoft.SharePoint.Deployment.SPImportSettings
	$settings.SiteUrl = $job.DestinationSiteUrl
	$settings.WebUrl = $job.DestinationWebUrl
	$settings.FileLocation = $token.Directory
	$settings.BaseFileName = $job.Name+".cmp"
	$settings.CommandLineVerbose = $true;
	$settings.UserInfoDateTime = [Microsoft.SharePoint.Deployment.SPImportUserInfoDateTimeOption]::ImportAll
	
	if ( (Test-Path ($systemDataFile = $($settings.FileLocation) + "\\SystemData.xml")))
	{
		if ( (Test-Path ($($settings.FileLocation) + "\\Backup_SystemData.xml")) -eq $false){
			copy-item  "$($settings.FileLocation)\\SystemData.xml" "$($settings.FileLocation)\\Backup_SystemData.xml"
		}	
		$SystemData = [xml](Get-Content -Path $systemDataFile)
	}

	if ( (Test-Path ($RequirementsFile = $($settings.FileLocation) + "\\Requirements.xml")))
	{
		$Requirements = [xml](Get-Content -Path $RequirementsFile)
		
		if ( (Test-Path ($($settings.FileLocation) + "\\Backup_Requirements.xml")) -eq $false){
			copy-item  "$($settings.FileLocation)\\Requirements.xml" "$($settings.FileLocation)\\Backup_Requirements.xml"
		}	
	}
	
	if ( (Test-Path ($ExportSettingsFile = $($settings.FileLocation) + "\\ExportSettings.xml")))
	{
		$ExportSettings = [xml](Get-Content -Path $ExportSettingsFile)
	}
	
	if ( (Test-Path ($ManifestFile = $($settings.FileLocation) + "\\Manifest.xml")))
	{
		$Manifest = [xml](Get-Content -Path $ManifestFile)
		if ( (Test-Path ($($settings.FileLocation) + "\\Backup_Manifest.xml")) -eq $false){
			copy-item  "$($settings.FileLocation)\\Manifest.xml" "$($settings.FileLocation)\\Backup_Manifest.xml"
		}
	}
	
	Write-Host "`nJob details" -ForeGroundColor green
	Write-Host "$($job.Name) type $($job.type)" -foregroundcolor yellow
	Write-Host "From: $($ExportSettings.ExportSettings.SiteUrl)" -foregroundcolor yellow
	Write-Host "To: $($job.DestinationSiteUrl)" -foregroundcolor yellow
	
	
	Write-Host "`nUsing token" -ForeGroundColor green
	Write-Host "Content export mode: $($token.mode) from $([DateTime]::Parse($token.timestamp))"	-foregroundcolor yellow
	
	Write-Host "`nPackage details" -Foregroundcolor green
	Write-Host "Processing $($SystemData.SystemData.SchemaVersion.ObjectsProcessed) objects" -ForeGroundColor yellow
	Write-Host "Content from build version $($SystemData.SystemData.SchemaVersion.Build)" -ForeGroundColor yellow
	
	Write-Host "`nParameters" -ForeGroundColor green
	Write-Host "Retain object IDs: $($job.RetainObjectIdentity)" -foregroundcolor yellow
	Write-Host "Force deployment to version: $OverrideSchemaVersion" -foregroundcolor yellow
	Write-Host "Skip requirements: $IgnoreRequirements" -foregroundcolor yellow
	Write-Host "Remove existing site collection: $ReCreateSiteCollection"-foregroundcolor yellow
	Write-Host "Create required site collection: $CreateIfNotExistSiteCollection" -foregroundcolor yellow
	Write-Host "Reset to default masterpage: $DefaultMasterPage`n" -foregroundcolor yellow
	
	# Run Import
	if ( $token.mode -eq "Full")
	{
		if ($job.Type -eq "Site")
		{
			if ($CreateIfNotExistSiteCollection -eq $true)
			{
				$site = Get-SPSite -Identity $job.DestinationSiteUrl
				if ($site -eq $null)
				{
					Write-Host "Creating sitecollection $($job.DestinationSiteUrl)" -Foregroundcolor yellow
					New-SPSite -Url $job.DestinationSiteUrl -Name $job.Name -OwnerAlias System
				}
				else
				{
					Write-Host "Sitecollection already exist $($job.DestinationSiteUrl)" -Foregroundcolor red
					break;
				}
			}
			
			if ($ReCreateSiteCollection -eq $true)
			{
				$site = Get-SPSite $job.DestinationSiteUrl
				if ($site -ne $null)
				{
					Write-Host "Removing existing sitecollection $($job.DestinationSiteUrl)" -Foregroundcolor yellow
					Remove-SPSite $job.DestinationSiteUrl -Confirm:$false
					Write-Host "Creating sitecollection $($job.DestinationSiteUrl)" -Foregroundcolor yellow
					New-SPSite -Url $job.DestinationSiteUrl -Name $job.Name -OwnerAlias System
				}
			}
				# Check if site exist
			if ( (Get-SPSite $job.DestinationSiteUrl) -eq $null)
			{
				Write-Host "Sitecollection does not exist." -ForeGroundColor Red
				break;
			
			}
		}
		elseif($job.Tpye -eq "List")
		{
			Write-Host "Cleaning destination lists"
			$web = Get-SPWeb $job.DestinationWebUrl
			foreach($jobItem in $job.JobItems.JobItem)
			{
			
				if (($list = $web.Lists | ? {$_.RootFolder.Name -eq $jobItem.Name} ) -eq $null)
				{
					if (($list = $web.Lists | ? {$_.Title -eq $jobItem.Name}) -eq $null)
					{
						Write-Host "List $($jobItem.Name) not found."
						continue;
					}
				}
				if ( $list -ne $null )
				{
					$list.Delete()
					Write-Host "Cleaned $($jobItem.Name)"
				}
			}
			$web.Update()
			$web.Dispose()
		}
	}
	

	$job.ImportUserInfoDateTimeOption

	
	if ( $job.FileCompression -eq "1")		
	{
		$settings.FileCompression = $true;
		$settings.FileCompression = $false;
		Write-Host "File compression has been disabled in this version"
	}			else	{$settings.FileCompression = $false}
	if ( $job.RetainObjectIdentity -eq "1")	{$settings.RetainObjectIdentity = $true}	else	{$settings.RetainObjectIdentity = $false}
	
	$import = New-Object Microsoft.SharePoint.Deployment.SPImport($settings);
	
	# EVENT Section
	# Error
	$Error = {
		$object = [Microsoft.SharePoint.Deployment.SPDeploymentErrorEventArgs]$eventArgs 
		
		$errorType = $object.ErrorType.ToString()
		$errorMessgae = $object.ErrorMessage
		$objecttype = $object.DeploymentObject.Type.ToString()
		$parentId = $object.DeploymentObject.ParentId
		
		Write-Host $errorType " - " $objecttype " - " $ErrorMessage " - " $parentId
		
		if ( ($object.DeploymentObject.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentErrorType]::Error)-or ($object.DeploymentObject.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentErrorType]::FatalError) )
		{
			Write-Host "Fatal error detected, this import operation will be marked as failed." -Foregroundcolor Red
			$fatalError = $true
		}
	}
	# Started
	$Started	 = {
		$object = [Microsoft.SharePoint.Deployment.SPDeploymentEventArgs]$eventArgs

		Write-Host "Beginning import"

		$object.ObjectsTotal 
		$rootObjects = $object.RootObjects
		foreach($item in $rootObjects)
		{
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::List)
			{
				Write-Host "Re-Parent List $item" -foregroundcolor green
				$item.TargetParentUrl = $XmlConfig.Root.ContentDeployment.Export.DestinationWebUrl
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::ListItem)
			{
				Write-Host "Re-Parent ListItem $item" -foregroundcolor green
				
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::File)
			{
				Write-Host "Re-Parent File $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Folder)
			{
				Write-Host "Re-Parent Folder $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Web)
			{
				Write-Host "Re-Parent Web $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Site)
			{
				Write-Host "Re-Parent Site $item" -foregroundcolor green
			}
		}
	}
	  
	# Uncompressing
	$Uncompressing	 = {
		$object = [Microsoft.SharePoint.Deployment.SPDeploymentEventArgs]$eventArgs

		Write-Host "Uncompressing objects";
	}
	# ProgressUpdated
	$ProgressUpdated	 = {
		$object = [Microsoft.SharePoint.Deployment.SPDeploymentEventArgs]$eventArgs

		Write-Host "." -NoNewLine
	}
	# ObjectImported 
	$ObjectImported = {
		$object = [Microsoft.SharePoint.Deployment.SPObjectImportedEventArgs]$eventArgs;
		
		if ($job.Type -eq "Site")
		{continue;}
		$rootObjects = $object.RootObjects
		foreach($item in $rootObjects)
		{
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::List)
			{
				Write-Host "Re-Parent $item" -foregroundcolor green
				$item.TargetParentUrl = $XmlConfig.Root.ContentDeployment.Export.DestinationWebUrl
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::ListItem)
			{
				Write-Host "Re-Parent ListItem $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::File)
			{
				Write-Host "Re-Parent File $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Folder)
			{
				Write-Host "Re-Parent Folder $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Web)
			{
				Write-Host "Re-Parent Web $item" -foregroundcolor green
			}
			
			if ( $item.Type -eq [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Site)
			{
				Write-Host "Re-Parent Site $item" -foregroundcolor green
			}
		}
	}
	
	Register-ObjectEvent -InputObject $import -EventName ObjectImported -Action $ObjectImported
	Register-ObjectEvent -InputObject $import -EventName Error -Action $Error
	Register-ObjectEvent -InputObject $import -EventName ProgressUpdated -Action $ProgressUpdated
	Register-ObjectEvent -InputObject $import -EventName Started -Action $Started
	Register-ObjectEvent -InputObject $import -EventName Uncompressing -Action $Uncompressing
 
	$token
	$job
	
	# Setting lookups
	
	if ( (Test-Path ($lookupFile = $($settings.FileLocation) + "\\LookupListMap.xml"))-and($token.Mode -eq "Incremental"))
	{
		if ( (Test-Path ($($settings.FileLocation) + "\\Backup_LookupListMap.xml")) -eq $false){
			copy-item  "$($settings.FileLocation)\\LookupListMap.xml" "$($settings.FileLocation)\\Backup_LookupListMap.xml"
		}
		Write-Host "Fixing Lookups for the Incremental Operation" -ForeGroundColor yellow

		$sourceRelativeListPath = ($sTmp=[string]$job.WebUrl.Substring($job.WebUrl.indexof("//")+2)).Substring($sTmp.IndexOf("/")).TrimEnd("/")
		$destRelativeListPath = ($dTmp=[string]$job.DestinationWebUrl.Substring($job.DestinationWebUrl.indexof("//")+2)).Substring($dTmp.IndexOf("/")).TrimEnd("/")
		
		(Get-Content $lookupFile | ForEach-Object {$_ -replace ($sourceRelativeListPath,$destRelativeListPath)} ) | Set-Content $lookupFile
	}
	
	# Adjusting schema version
	if ( $OverrideSchemaVersion.length -gt 0)
	{
		Write-Host "Overriding schema version $($SystemData.SystemData.SchemaVersion.Version) to $OverrideSchemaVersion" -ForeGroundColor yellow

		$SystemData.SystemData.SchemaVersion.Version = [string]$OverrideSchemaVersion
			
		
		$SystemData.Save($systemDataFile)
	}

    if ($IgnoreRequirements -eq $true)
    {
		Write-Host "Clearing requirements" -ForeGroundColor yellow
		$Requirements.Requirement

		$Requirements.Requirements.RemoveAll()
			
		$Requirements.Save($RequirementsFile)
    }
		
	$import.Run()
	sleep 10
	
	Write-Host "Asynchronous jobs may still run. Leave the console open and wait a few minutes." -Foregroundcolor red
	
	if ( $fatalError -eq $false ){Change-TokenImportedStatus -Timestamp $token.Timestamp -Imported $true }

	# Landingpage fix for root web
	$site = Get-SPSite $settings.SiteUrl
	$web = $site.RootWeb
	foreach($object in $Manifest.SPObjects.SPObject)
	{
		if ( $object.Folder -ne $null)
		{
			if ($object.Folder.ParentFolderId -eq "00000000-0000-0000-0000-000000000000")
			{
				$web.RootFolder.WelcomePage = $object.Folder.WelcomePageUrl;
				$web.Update()
				break;
			}
		}
	}

	if ($DefaultMasterPage -eq $true) 
	{
	$web.MasterUrl =  $web.ServerRelativeUrl + "/_catalogs/masterpage/v4.master"
	$web.Update()
	}

}


